package com.yangyang.androidconnect.service;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.yangyang.androidconnect.database.FileIndexDao;
import com.yangyang.androidconnect.vo.response.FileInfo;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

public class FileIndexService {

    private static final String TAG = "FileIndexService";
    private static final AtomicBoolean isIndexing = new AtomicBoolean(false);

    private final Context context;
    private final FileIndexDao fileIndexDao;
    private IndexingListener indexingListener;

    // 添加索引监听接口
    public interface IndexingListener {
//        void onIndexingStarted();
//        void onIndexingProgress(int progress, int total);
//        void onIndexingCompleted(boolean success, int totalFiles);
//        void onIndexingError(String errorMessage);

        void onIndexingStarted();
        void onIndexingCompleted(boolean success, int totalFiles);
        void onIndexingError(String errorMessage);
    }

    public FileIndexService(Context context) {
        this.context = context.getApplicationContext();
        this.fileIndexDao = new FileIndexDao(context);
    }

    // 设置监听器
    public void setIndexingListener(IndexingListener listener) {
        this.indexingListener = listener;
    }

    // 开始索引（异步）
    public void startIndexing(String rootPath) {
        if (isIndexing.get()) {
            Log.w(TAG, "Indexing is already in progress");
            return;
        }

        new IndexingTask().execute(rootPath);
    }

    // 检查是否正在索引
    public boolean isIndexing() {
        return isIndexing.get();
    }

    // 获取文件列表（从数据库）
    public FileListResult getFileList(String path, int page, int pageSize, String sortBy, boolean ascending) {
        try {
            int total = fileIndexDao.getFileCount(path);
            List<FileInfo> files = fileIndexDao.getFilesByParentPath(path, page, pageSize, sortBy, ascending);

            return new FileListResult(files, total, page, pageSize);
        } catch (Exception e) {
            Log.e(TAG, "Error getting file list from database", e);
            return new FileListResult(new ArrayList<>(), 0, page, pageSize);
        }
    }

    // 异步索引任务
    private class IndexingTask extends AsyncTask<String, Void, IndexingResult> {
        private int totalFiles = 0;

        @Override
        protected void onPreExecute() {
            isIndexing.set(true);
            Log.i(TAG, "Starting file indexing...");

            if (indexingListener != null) {
                indexingListener.onIndexingStarted();
            }
        }

        @Override
        protected IndexingResult doInBackground(String... paths) {
            if (paths == null || paths.length == 0) return new IndexingResult(false, 0, "路径为空");

            String rootPath = paths[0];
            try {
                fileIndexDao.clearAll(); // 清空旧数据
                indexDirectoryRecursive(new File(rootPath), rootPath);
                return new IndexingResult(true, totalFiles, "索引完成");
            } catch (Exception e) {
                Log.e(TAG, "Error during indexing", e);
                return new IndexingResult(false, totalFiles, "索引失败: " + e.getMessage());
            }
        }

        @Override
        protected void onPostExecute(IndexingResult result) {
            isIndexing.set(false);
            if (result.success) {
                Log.i(TAG, "File indexing completed successfully");

                if (indexingListener != null) {
                    indexingListener.onIndexingCompleted(true, result.totalFiles);
                }
            } else {
                Log.e(TAG, "File indexing failed");

                if (indexingListener != null) {
                    indexingListener.onIndexingError(result.errorMessage);
                }
            }
        }

        // 递归索引目录
        private void indexDirectoryRecursive(File directory, String rootPath) {
            if (directory == null || !directory.exists() || !directory.isDirectory()) {
                return;
            }

            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    // 跳过隐藏文件
                    if (file.getName().startsWith(".")) {
                        continue;
                    }

                    // 插入当前文件/目录
                    String parentPath = file.getParent() != null ? file.getParent() : rootPath;
                    fileIndexDao.insertOrUpdateFile(file, parentPath);

                    totalFiles++;

                    // 如果是目录，递归索引
                    if (file.isDirectory()) {
                        indexDirectoryRecursive(file, rootPath);
                    }

                    // 检查是否被取消
                    if (isCancelled()) {
                        return;
                    }
                }
            }
        }
    }

    // 索引结果封装类
    private static class IndexingResult {
        boolean success;
        int totalFiles;
        String errorMessage;

        IndexingResult(boolean success, int totalFiles, String errorMessage) {
            this.success = success;
            this.totalFiles = totalFiles;
            this.errorMessage = errorMessage;
        }
    }


    // 文件列表结果封装类
    public static class FileListResult {
        public final List<FileInfo> files;
        public final int total;
        public final int page;
        public final int pageSize;

        public FileListResult(List<FileInfo> files, int total, int page, int pageSize) {
            this.files = files;
            this.total = total;
            this.page = page;
            this.pageSize = pageSize;
        }
    }
}